﻿<UserControl x:Class="FR.SAFTAnalyser.Views.InvoicesView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:Controls="clr-namespace:MahApps.Metro.Controls;assembly=MahApps.Metro"
             xmlns:v="clr-namespace:FR.SAFTAnalyser.SAFT.Validations"
             xmlns:conv="clr-namespace:FR.SAFTAnalyser.Converters"
             mc:Ignorable="d">

    <UserControl.Resources>
        <conv:BoolToVisibilityConverter x:Key="BoolToVisibilityConverter"/>
    </UserControl.Resources>
    
    <Grid HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="350"/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="*"/>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <Grid.Resources>
            <CollectionViewSource x:Key="invoices" Source="{Binding Invoices, IsAsync=True}">
                <CollectionViewSource.GroupDescriptions>
                    <PropertyGroupDescription PropertyName="InvoiceType"/>
                </CollectionViewSource.GroupDescriptions>
            </CollectionViewSource>
        </Grid.Resources>

        <DockPanel Grid.Row="0" Grid.Column="0">

            <DockPanel DockPanel.Dock="Top">
                <Label Content="Documentos" DockPanel.Dock="Left" Margin="3" />

                <TextBox DockPanel.Dock="Right" Margin="3" TabIndex="2"
                         Controls:TextboxHelper.Watermark="Coloque aqui um filtro de pesquisa" 
                         Controls:TextboxHelper.ClearTextButton="True"
                         Text="{Binding FilterInvoices, UpdateSourceTrigger=PropertyChanged}" />
            </DockPanel>

            <DataGrid x:Name="dataGridInvoices" DockPanel.Dock="Bottom" TabIndex="1" VirtualizingPanel.IsVirtualizingWhenGrouping="True"
                      ItemsSource="{Binding Source={StaticResource invoices}}" 
                      SelectedItem="{Binding CurrentInvoice}" SelectionChanged="dataGridInvoices_SelectionChanged">

                <DataGrid.RowValidationRules>
                    <v:InvoiceValidationRule ValidationStep="ConvertedProposedValue" ValidatesOnTargetUpdated="True"/>
                </DataGrid.RowValidationRules>

                <DataGrid.RowValidationErrorTemplate>
                    <ControlTemplate>
                        <Grid Margin="0,-2,0,-2"
                              ToolTip="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGridRow}},
                            Path=(Validation.Errors)[0].ErrorContent}">
                            <Ellipse StrokeThickness="0" Fill="Red" 
                                     Width="{TemplateBinding FontSize}" 
                                     Height="{TemplateBinding FontSize}" />
                        </Grid>
                    </ControlTemplate>
                </DataGrid.RowValidationErrorTemplate>

                <DataGrid.Columns>
                    <DataGridTextColumn Header="No" Binding="{Binding InvoiceNo}" Width="70"/>
                    <DataGridTextColumn Header="Estado" Binding="{Binding DocumentStatus.InvoiceStatus}" Width="50" />
                    <DataGridTextColumn Header="Data documento" Binding="{Binding InvoiceDate}" />
                    <DataGridTextColumn Header="Data sistema" Binding="{Binding SystemEntryDate}" />
                    <DataGridTextColumn Header="Total s/ IVA" Binding="{Binding DocumentTotals.NetTotal}" Width="100"/>
                    <DataGridTextColumn Header="Total" Binding="{Binding DocumentTotals.GrossTotal}" Width="70"/>
                    <DataGridTextColumn Header="Total imposto" Binding="{Binding DocumentTotals.TaxPayable}" Width="100"/>
                    <DataGridTextColumn Header="Cliente" Binding="{Binding CustomerID}" Width="80"/>
                    <DataGridTextColumn Header="Periodo" Binding="{Binding Period}" Width="75"/>
                    <DataGridTextColumn Header="Autofacturação" Binding="{Binding SelfBillingIndicator}" Width="105"/>
                    <DataGridTextColumn Header="Transacção" Binding="{Binding TransactionID}" />
                    <DataGridTextColumn Header="Hash" Binding="{Binding Hash}" />
                    <DataGridTextColumn Header="Hash Test" Binding="{Binding HashTest}" />
                    <DataGridTextColumn Header="Hash Control" Binding="{Binding HashControl}" />
                </DataGrid.Columns>

                <DataGrid.GroupStyle>
                    <GroupStyle>
                        <GroupStyle.HeaderTemplate>
                            <DataTemplate>
                                <StackPanel>
                                    <TextBlock Text="{Binding Path=Name}" />
                                </StackPanel>
                            </DataTemplate>
                        </GroupStyle.HeaderTemplate>
                        <GroupStyle.ContainerStyle>
                            <Style TargetType="{x:Type GroupItem}">
                                <Setter Property="Template">
                                    <Setter.Value>
                                        <ControlTemplate TargetType="{x:Type GroupItem}">
                                            <Expander IsExpanded="True">
                                                <Expander.Header>
                                                    <StackPanel Orientation="Horizontal">
                                                        <TextBlock Text="{Binding Path=Name}" Foreground="{StaticResource Foreground}"/>
                                                        <TextBlock Text=" ( " Foreground="{StaticResource Foreground}"/>
                                                        <TextBlock Text="{Binding Path=ItemCount}" Foreground="{StaticResource Foreground}"/>
                                                        <TextBlock Text=" )" Foreground="{StaticResource Foreground}"/>
                                                    </StackPanel>
                                                </Expander.Header>
                                                <ItemsPresenter />
                                            </Expander>
                                        </ControlTemplate>
                                    </Setter.Value>
                                </Setter>
                            </Style>
                        </GroupStyle.ContainerStyle>
                    </GroupStyle>
                </DataGrid.GroupStyle>
            </DataGrid>

        </DockPanel>

        <GridSplitter Grid.Row="1" Grid.ColumnSpan="2" Grid.Column="0" VerticalAlignment="Center" Margin="5"
                      Background="White" ShowsPreview="True" Height="5" ResizeDirection="Rows" />

        <DockPanel Grid.Row="2" Grid.Column="0" Grid.ColumnSpan="2">

            <DockPanel DockPanel.Dock="Top">
                <CheckBox Content="Mostrar todas as linhas"  DockPanel.Dock="Left" Margin="5,9,5,5" Foreground="White"
                          IsChecked="{Binding ShowAllLines, Mode=TwoWay}"/>
                
                <Label Content="Linhas" DockPanel.Dock="Left" Margin="3" />
                <TextBox DockPanel.Dock="Right" Margin="3" TabIndex="2"
                         Controls:TextboxHelper.Watermark="Coloque aqui um filtro de pesquisa" 
                         Controls:TextboxHelper.ClearTextButton="True"
                         Text="{Binding FilterLines, UpdateSourceTrigger=PropertyChanged}" />
            </DockPanel>

            <DataGrid x:Name="dataGridInvoiceLines" DockPanel.Dock="Bottom" 
                      ItemsSource="{Binding CurrentInvoiceLines, IsAsync=True}"
                      SelectedItem="{Binding CurrentInvoiceLine}" SelectionChanged="dataGridInvoiceLines_SelectionChanged">
                <DataGrid.RowValidationRules>
                    <v:InvoiceLineValidationRule ValidationStep="ConvertedProposedValue" ValidatesOnTargetUpdated="True"/>
                </DataGrid.RowValidationRules>

                <DataGrid.RowValidationErrorTemplate>
                    <ControlTemplate>
                        <Grid Margin="0,-2,0,-2"
                              ToolTip="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGridRow}},
                            Path=(Validation.Errors)[0].ErrorContent}">
                            <Ellipse StrokeThickness="0" Fill="Red" 
                                     Width="{TemplateBinding FontSize}" 
                                     Height="{TemplateBinding FontSize}" />
                        </Grid>
                    </ControlTemplate>
                </DataGrid.RowValidationErrorTemplate>

                <DataGrid.Columns>
                    <DataGridTextColumn Header="Nº linha" Binding="{Binding LineNumber}" Width="60"/>
                    <DataGridTextColumn Header="Nº documento" Binding="{Binding InvoiceNo}"
                                        Visibility="{Binding ShowAllLines, Converter={StaticResource BoolToVisibilityConverter}}" Width="60"/>
                    <DataGridTextColumn Header="Código produto" Binding="{Binding ProductCode}" />
                    <DataGridTextColumn Header="Descrição produto" Binding="{Binding ProductDescription}" />
                    <DataGridTextColumn Header="Quantidade" Binding="{Binding Quantity}"/>
                    <DataGridTextColumn Header="Preço unitário" Binding="{Binding UnitPrice}" />
                    <DataGridTextColumn Header="Valor" Binding="{Binding Item}" />
                    <DataGridTextColumn Header="Tipo operação" Binding="{Binding ItemElementName}" />
                    <DataGridTextColumn Header="Imposto" Binding="{Binding Tax.Item}"/>
                    <DataGridTextColumn Header="Isenção imposto" Binding="{Binding TaxExemptionReason}"  />
                    <DataGridTextColumn Header="Unidade medida" Binding="{Binding UnitOfMeasure}" />
                    <DataGridTextColumn Header="Data" Binding="{Binding TaxPointDate, IsAsync=True, StringFormat=\{0:d\}}"  />
                    <DataGridTextColumn Header="Descrição" Binding="{Binding Description}" />
                </DataGrid.Columns>
            </DataGrid>

        </DockPanel>

        <DockPanel Grid.Row="0" Grid.Column="1" MinHeight="300" MinWidth="300">
            <GroupBox Header="Totais" Margin="5" Padding="3" DockPanel.Dock="Top">
                <Grid>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="Auto" />
                        <ColumnDefinition Width="Auto" />
                        <ColumnDefinition Width="Auto" />
                        <ColumnDefinition Width="Auto" />
                    </Grid.ColumnDefinitions>
                    <Grid.RowDefinitions>
                        <RowDefinition Height="Auto" />
                        <RowDefinition Height="Auto" />
                        <RowDefinition Height="Auto" />
                        <RowDefinition Height="Auto" />
                        <RowDefinition Height="Auto" />
                        <RowDefinition Height="Auto" />
                        <RowDefinition Height="Auto" />
                        <RowDefinition Height="Auto" />
                    </Grid.RowDefinitions>

                    <TextBlock Text="Totais SAFT:" Grid.Column="0" Grid.Row="0" Grid.ColumnSpan="3" FontSize="14" FontWeight="SemiBold" Margin="3"/>

                    <TextBlock Text="Documentos:" Grid.Column="0" Grid.Row="1" Margin="3"/>
                    <TextBlock Text="Total crédito:" Grid.Column="0" Grid.Row="2" Margin="3"/>
                    <TextBlock Text="Total débito:" Grid.Column="0" Grid.Row="3" Margin="3"/>
                    <TextBlock Text="Total:" Grid.Column="2" Grid.Row="1" Margin="3"/>
                    <TextBlock Text="Total s/ IVA:" Grid.Column="2" Grid.Row="2" Margin="3"/>
                    <TextBlock Text="Total IVA:" Grid.Column="2" Grid.Row="3" Margin="3"/>

                    <TextBlock Text="{Binding NumberOfEntries}" Grid.Column="1" Grid.Row="1" Margin="3" />
                    <TextBlock Text="{Binding TotalCredit}" Grid.Column="1" Grid.Row="2" Margin="3"/>
                    <TextBlock Text="{Binding TotalDebit}" Grid.Column="1" Grid.Row="3" Margin="3"/>
                    <TextBlock Text="{Binding GrossTotal}" Grid.Column="3" Grid.Row="1" Margin="3" />
                    <TextBlock Text="{Binding NetTotal}" Grid.Column="3" Grid.Row="2" Margin="3"/>
                    <TextBlock Text="{Binding TaxPayable}" Grid.Column="3" Grid.Row="3" Margin="3"/>

                    <TextBlock Text="Soma valores:" Grid.Column="0" Grid.Row="4" Grid.ColumnSpan="2" FontSize="14" FontWeight="SemiBold" Margin="3" />

                    <TextBlock Text="Documentos:" Grid.Column="0" Grid.Row="5" Margin="3"/>
                    <TextBlock Text="Total crédito:" Grid.Column="0" Grid.Row="6" Margin="3"/>
                    <TextBlock Text="Total débito:" Grid.Column="0" Grid.Row="7" Margin="3"/>
                    <TextBlock Text="Total:" Grid.Column="2" Grid.Row="5" Margin="3"/>
                    <TextBlock Text="Total s/ IVA:" Grid.Column="2" Grid.Row="6" Margin="3"/>
                    <TextBlock Text="Total IVA:" Grid.Column="2" Grid.Row="7" Margin="3"/>

                    <TextBlock Text="{Binding DocNumberOfEntries}" Grid.Column="1" Grid.Row="5" Margin="3" />
                    <TextBlock Text="{Binding DocTotalCredit}" Grid.Column="1" Grid.Row="6" Margin="3"/>
                    <TextBlock Text="{Binding DocTotalDebit}" Grid.Column="1" Grid.Row="7" Margin="3"/>
                    <TextBlock Text="{Binding DocGrossTotal}" Grid.Column="3" Grid.Row="5" Margin="3" />
                    <TextBlock Text="{Binding DocNetTotal}" Grid.Column="3" Grid.Row="6" Margin="3"/>
                    <TextBlock Text="{Binding DocTaxPayable}" Grid.Column="3" Grid.Row="7" Margin="3"/>

                </Grid>
            </GroupBox>

            <Button Width="150" Height="25" Margin="5" Padding="3" ToolTip="Exportar para Excel" DockPanel.Dock="Bottom" 
                        Command="{Binding DoOpenExcelCommand}">
                <StackPanel Orientation="Horizontal">
                    <Image Source="..\Resources\excel.ico"/>
                    <TextBlock Text="Documento" Padding="3"/>
                </StackPanel>
            </Button>
        </DockPanel>
    </Grid>

</UserControl>
